package com.example.day2.exercise;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * 使用函数接口解决问题
 */
public class Exercise3 {
    public static void main(String[] args) {
        System.out.println(filter(List.of(1, 2, 3, 4, 5, 6), number -> (number & 1) == 0)); // 筛选偶数
        System.out.println(filter(List.of(1, 2, 3, 4, 5, 6), number -> (number & 1) == 1)); // 筛选奇数

        // System.out.println(map(List.of(1, 2, 3, 4, 5, 6), number -> String.valueOf(number)));
        System.out.println(map(List.of(1, 2, 3, 4, 5, 6), String::valueOf)); // 使用方法引用简化

        // consume(List.of(1, 2, 3, 4, 5, 6), (number) -> System.out.println(number));
        consume(List.of(1, 2, 3, 4, 5, 6), System.out::println); // 使用方法引用简化

        System.out.println(supply(5, () -> ThreadLocalRandom.current().nextInt()));
    }

    static List<Integer> filter(List<Integer> list, Predicate<Integer> predicate) {
        List<Integer> result = new ArrayList<>();
        for (Integer number : list) {
            // 筛选:判断是否是偶数,但以后可能改变筛选规则
            if (predicate.test(number)) {
                result.add(number);
            }
        }
        return result;
        /*
            有一个参数,返回值类型是boolean 使用Predicate函数式接口
            (Integer number) -> (number & 1) == 0
         */
    }

    static List<String> map(List<Integer> list, Function<Integer, String> function) {
        List<String> result = new ArrayList<>();
        for (Integer number : list) {
            // 转换:将数字转为字符串,但以后可能改变转换规则
            result.add(function.apply(number));
        }
        return result;
        /*
            接收一个参数,返回值类型是String 有参有返回值 -> Function
            (Integer number) -> String.valueOf(number)
         */
    }

    static void consume(List<Integer> list, Consumer<Integer> consumer) {
        for (Integer number : list) {
            // 消费:打印,但以后可能改变消费规则
            consumer.accept(number);
        }
        /*
            一个参数,无返回类型 -> Consumer
            (Integer number) -> System.out.println(number)
         */
    }

    static List<Integer> supply(int count, Supplier<Integer> supplier) {
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            // 生成:随机数,但以后可能改变生成规则
            result.add(supplier.get());
        }
        return result;
    }
    /*
        没有参数 有返回值 -> Supplier
        () -> ThreadLocalRandom.current().nextInt()
     */
}
